package com.zrong.project.manager;

import com.zrong.project.cache.Constants;
import org.apache.log4j.Logger;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 12-6-21
 * Time: 下午2:43
 * To change this template use File | Settings | File Templates.
 */
public abstract class AbstractPersistentManager<T> implements PersistentManager<T> {
    private static Logger logger = Logger.getLogger(AbstractPersistentManager.class);

    private volatile Queue<T> queue = new ConcurrentLinkedQueue<T>();
    private long eachCheckTime = 30000;
    private boolean runFlag = true;

    public abstract boolean persistentQueue(Queue<T> objects);

    public void persistentQueue() {
        int size = queue.size();
        logger.info(this.getClass().getName() + " persistentQueue starting,persistentQueue size is " + size);
        try {
            if (size > 0){
                persistentQueue(queue);
                queue.clear();
            }
        } catch (Exception e) {
            logger.error(this.getClass().getName() + " persistentQueue error", e);
        }
    }

    public void pushPersistentObject(T obj) {
        queue.offer(obj);
        if (queue.size() >= Constants.MAX_CACHE_SIZE) {
            synchronized (this) {
                this.notify();
            }
        }
    }

    public void run() {
        while (runFlag) {
            try {
                logger.info(this.getClass().getName() + " running ");
                persistentQueue();
                synchronized (this) {
                    this.wait(eachCheckTime);
                }
            } catch (InterruptedException e) {
                logger.error("Thread to be interrupted ", e);
            } catch (Exception e) {
                logger.error("Storage failure", e);
            }
        }
    }

    public long getEachCheckTime() {
        return eachCheckTime;
    }

    public void setEachCheckTime(long eachCheckTime) {
        this.eachCheckTime = eachCheckTime;
    }
}
